<template>
  <el-dialog
    class="subject-status-add-record"
    :title="dialogTitle"
    width="600px"
    :show-close="true"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <div>
      <el-form :rules="rules" ref="formRef" size="mini" :model="formData" label-width="140px">
        <el-form-item label="类型：" prop="type" v-if="dialogTitle === '新建'">
          <el-select v-model="formData.type" placeholder="请选择" style="width: 80%" @change="handleTypeChange">
            <el-option
              v-for="item in addTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型：" prop="type" v-else>
          <el-select
            v-model="formData.type"
            placeholder="请选择"
            :disabled="dialogTitle === '编辑'"
            style="width: 80%"
            @change="handleTypeChange"
          >
            <el-option
              v-for="item in editTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文本：" v-if="formData.type === '2'" prop="variableName">
          <el-input
            type="textarea"
            style="width: 80%"
            :rows="4"
            placeholder="请输入"
            v-model="formData.variableName"
          ></el-input>
        </el-form-item>
        <el-form-item label="内嵌：" prop="type" v-if="formData.type === '3'">
          <el-select v-model="formData.embeddedTable" placeholder="请选择" style="width: 80%">
            <el-option
              v-for="item in embeddedList"
              :key="item.surface + '##' + item.surfaceName"
              :label="item.surfaceName"
              :value="item.surface + '##' + item.surfaceName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片上传：" prop="type" v-if="formData.type === '4'">
          <el-upload
            disabled
            class="avatar-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="隐藏：" v-if="dialogTitle === '编辑'">
          <el-radio-group v-model="formData.hide">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button :loading="loading" size="small" type="primary" @click="handleSave">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { mapActions } from 'vuex'
import { addTypeList, editTypeList } from '../data'

export default {
  props: {
    editData: Object,
    dialogVisible: Boolean,
    dialogTitle: String,
    searchParams: Object,
  },
  data() {
    return {
      rules: {
        type: [{ required: true, message: '请选择', trigger: 'blur' }],
        embeddedSurface: [{ required: true, message: '请选择', trigger: 'blur' }],
        variableName: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      loading: false,
      defaultFormData: {
        variableName: '',
        type: '',
        embeddedTable: '',
        hide: '',
      },
      addTypeList,
      editTypeList,
      formData: {},
      embeddedList: [],
      imageUrl: '',
    }
  },

  watch: {
    dialogVisible(val) {
      if (val) {
        this.formData = this.editData.id ? { ...this.editData } : { ...this.defaultFormData, ...this.editData }
        if (this.formData.type === '3') {
          this.getEmbeddedList()
        }
      } else {
        this.formData = { ...this.defaultFormData }
      }
    },
  },

  methods: {
    ...mapActions('eCRFDesign', ['qryChildEmbeddedTable', 'addInterfaceDesign', 'editInterfaceDesign']),

    // 关闭取消
    handleClose() {
      this.formData = { ...this.defaultFormData }
      this.$emit('handleCancel')
    },

    // 保存提交
    handleSave() {
      this.loading = true
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const data = {
            ...this.formData,
            ...this.searchParams,
            surface: this.searchParams.surface,
            embeddedSurface: this.formData.embeddedTable.split('##')[0],
            embeddedSurfaceName: this.formData.embeddedTable.split('##')[1],
          }

          delete data.rowControl
          delete data.rowControlJson

          if (data.type === '1') {
            delete data.variableValue
          }

          if (data.type === '3') {
            data.variableName = this.formData.embeddedTable.split('##')[1]
          }

          if (data.id) {
            this.editInterfaceDesign({ data }).then(res => {
              const { code } = res
              if (code === 200) {
                this.$message({
                  message: '保存成功',
                  type: 'success',
                })
                this.$refs.formRef.resetFields()
                this.$emit('handleCancel', 'refresh')
              }
              this.loading = false
            })
          } else {
            this.addInterfaceDesign({ data }).then(res => {
              const { code } = res
              if (code === 200) {
                this.$message({
                  message: '保存成功',
                  type: 'success',
                })
                this.$refs.formRef.resetFields()
                this.$emit('handleCancel', 'refresh')
              }
              this.loading = false
            })
          }
        } else {
          this.loading = false
          return false
        }
      })
    },

    // 类型切换事件
    handleTypeChange(value) {
      console.log(value)
      if (value === '3') {
        this.getEmbeddedList()
      }
      if (value === '4') {
        this.$message.warning('图片上传功能开发中！')
      }
    },

    // 查询内嵌列表
    getEmbeddedList() {
      const params = {
        ...this.searchParams,
      }
      this.qryChildEmbeddedTable({ params }).then(res => {
        const { data, code, message } = res
        if (code === 200) {
          this.embeddedList = data
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
  },
}
</script>
<style lang="scss" scoped>
@import './add-interfacial.scss';
.avatar-uploader /deep/.el-upload {
  border: 1px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
